package com.wyc.serviceMap.remote;

import com.wyc.internalCommon.constant.AmapConfigConstant;
import com.wyc.internalCommon.request.PointDTO;
import com.wyc.internalCommon.request.PointUploadDTO;
import com.wyc.internalCommon.response.TrackResponse;
import com.wyc.internalCommon.result.ApiResult;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.net.URI;

/**
 * 轨迹上传api
 */
@Service
public class PointUploadClient {

    @Value("${amap.key}")
    private String amapKey;

    @Value("${amap.sid}")
    private String amapSid;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 轨迹上传
     * @param pointDTO
     * @return
     */
    public ApiResult upload(PointDTO pointDTO){
        // 拼接路径url
        StringBuilder urlBuilder = new StringBuilder();
        urlBuilder.append(AmapConfigConstant.TRACK_POINT_UPLOAD);
        urlBuilder.append("?");
        urlBuilder.append("key="+amapKey);
        urlBuilder.append("&");
        urlBuilder.append("sid="+amapSid);
        urlBuilder.append("&");
        urlBuilder.append("tid="+pointDTO.getTid());
        urlBuilder.append("&");
        urlBuilder.append("trid="+pointDTO.getTrid());
        urlBuilder.append("&");
        urlBuilder.append("points=");
        urlBuilder.append("%5B");
        PointUploadDTO[] points = pointDTO.getPoints();
        for (PointUploadDTO point : points) {
            urlBuilder.append("%7B");
            urlBuilder.append("%22location%22");
            urlBuilder.append("%3A");
            urlBuilder.append("%22"+point.getLocation()+"%22");
            urlBuilder.append("%2C");
            urlBuilder.append("%22locatetime%22");
            urlBuilder.append("%3A");
            urlBuilder.append(point.getLocatetime());
            urlBuilder.append("%7D");
        }
        urlBuilder.append("%5D");
        System.out.println("上传轨迹====="+urlBuilder.toString());
        // 请求路径拼接的字符需要用编码，编码调接口需要URI.ceate()识别
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(URI.create(urlBuilder.toString()), null, String.class);

        return ApiResult.success(responseEntity);

    }

}
